/****************************************************
          File Name:46-6-server.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Sat 13 Sep 2014 08:46:33 AM CST
*****************************************************/

#include"msg.h"
#include<signal.h>
#include<fcntl.h>
#include<sys/wait.h>

void dealing(int sig)
{
    int id;

    id=msgget(key,S_IRUSR);
    msgctl(id,IPC_RMID,NULL);
    signal(sig,SIG_DFL);
    raise(sig);
}

void transport(struct msgbuf msg)
{
    if(msgsnd(msg.id,&msg,DATA_SIZE,0)==-1)
        err("send message to user");
    exit(0);
}

int main(int argc,char *argv[])
{
    struct sigaction act;
    struct msgbuf msg;
    int server;
    int perm=S_IRUSR|S_IWUSR|S_IWGRP;
	int user[100];
	int i=0;

    if(sigemptyset(&act.sa_mask)==-1)
        err("sigemptyset");
    act.sa_flags=0;
    act.sa_handler=dealing;
	
	if(sigaction(SIGINT,&act,NULL)==-1 ||sigaction(SIGTERM,&act,NULL)==-1)
		err("set signal handler");

    if((server=msgget(key,IPC_CREAT|perm))==-1)
        err("creat msgid");

    msg.mtype=1;        // test

    for(;;)
    {
		if(msgrcv(server,&msg,DATA_SIZE,1,0)==-1)    // wait && block
			err("msgrcv");
		else
		{
			switch(fork())
            {
                case -1:
                    err("fork");
                case 0:
                    transport(msg);
                    break;
                default:
                    if(wait(NULL)==-1)
                        err("wait");
                    break;
			}
		}
    }

    exit(0); // will never run
}
